<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Refund;
use app\common\model\fittings\After;
use app\common\model\fittings\Order;
use app\common\model\fittings\Category;
use app\common\model\fittings\Fittings as FittingsFittings;
use app\common\model\fittings\Review;
use app\common\model\user\Address;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 配件接口
 */
class Fittings extends Api
{
    protected $noNeedLogin = ['category', 'lists', 'info','review_list'];
    protected $noNeedRight = ['*'];

    /**
     * @Author LK
     * @ApiTitle (配件分类)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function category()
    {
        $list = Category::all(['pid' => 0]);
        $this->success('请求成功', $list);
    }

    /**
     * @Author LK
     * @ApiTitle (配件列表)
     * @ApiMethod (GET)
     * @ApiParams (name="first_id", type="integer", required=true, sample="", description="一级分类")
     * @ApiParams (name="two_id", type="integer", required=true, sample="", description="二级分类")
     * @ApiParams (name="keywords", type="string", required=true, sample="", description="关键字")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function lists()
    {
        $param = request()->param();
        extract($param);
        $model = new FittingsFittings();
        if (isset($keywords) && $keywords) {
            $model->whereLike('title', $keywords);
        }
        if ($first_id && $two_id) {
            $model->where('c_id', $two_id);
        }
        if ($first_id && !$two_id) {
            // $cate_ids = Category::whereIn('pid', $first_id)->column('id');
            $model->where('f_id', $first_id);
        }
        $lists = $model->order('id desc')->paginate();
        $this->success('请求成功', $lists);
    }


    /**
     * @Author LK
     * @ApiTitle (配件详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="id")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function info()
    {
        $param = request()->param();
        extract($param);
        $data = FittingsFittings::get($id);
        $this->success('', $data);
    }
    /**
     * @Author LK
     * @ApiTitle (配件下单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="num", type="integer", required=true, sample="", description="购买数量")
     * @ApiParams (name="deliver", type="integer", required=true, sample="", description="配送方式:1=快递到家")
     * @ApiParams (name="address_id", type="integer", required=fasle, sample="", description="收货地址")
     * @ApiParams (name="mark", type="string", required=fasle, sample="", description="备注")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */

    public function addOrder()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $data = FittingsFittings::get($id);
        $data->hidden(['id']);
        if (!$data) {
            $this->error('产品不存在');
        }
        Db::startTrans();
        try {
            $data = $data->toArray();
            $data['m_id'] = $id;
            $data['num'] = $num;
            $data['pay_price'] = bcmul($data['price'], $data['num'], 2);
            $data['sn'] = sn('lease_order', 'sn', 'FT');
            $data['user_id'] = $this->auth->id;
            $data['createtime'] = time();
            $data['mark'] = $mark;
            if (isset($address_id) && !empty($address_id)) {
                $addressInfo = Address::get($address_id);
            } else {
                $addressInfo = Address::getDefaultAddress($user_id);
            }
            if ($addressInfo) {
                $data['contact']  = $addressInfo['contact'];
                $data['telephone']  = $addressInfo['telephone'];
                $data['address_id']  = $addressInfo['id'];
                $data['address']  = $addressInfo['province'] . $addressInfo['city'] . $addressInfo['area'] . $addressInfo['address'];
            } else {
                exception('请选择收货地址');
            }
            $order = new Order();
            $order->isUpdate(false)->allowField(true)->save($data);
            queue('app\common\job\FittingsOrder', $order->id, 300, '1255FittingsOrder');
            Db::commit();
            $this->success('下单成功', $order->id);
        } catch (Exception $th) {
            //throw $th;
            Db::rollback();
            $this->error('下单失败', $th);
        }
    }


    /**
     * @Author LK
     * @ApiTitle (配件订单)
     * @ApiMethod (GET)
     * @ApiParams (name="status", type="integer", required=true, sample="", description="改装状态:all=全部,0=待支付,1=待发货,2=待收货,3=已完成")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_list()
    {

        $param = request()->param();
        extract($param);
        $model = new Order();
        if (in_array($status, ['0', '1', '2'])) {
            $model->where('status', $status);
        }
        if ($status == '3') {
            $model->whereIn('status', ['3', '4']);
        }
        $lists = $model->where('user_id', $this->auth->id)->where('refund_status','0')->whereNotIn('status', ['5', '-1'])->order('id desc')->paginate();
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (售后订单)
     * @ApiMethod (GET)
     * @ApiParams (name="status", type="integer", required=true, sample="", description="售后状态:1=待申请,2=处理中,3=已处理")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function after_sale_list()
    {
        $param = request()->param();
        extract($param);
        $model = new Order();
        if ($status == '1') {
            $model->where('status', '>', '0');
            $model->where('sale_status', '0');
        } elseif ($status == '2') {
            $model->where('refund_status', '1');
        } else {
            $model->where('refund_status', '2');
        }
        $lists = $model->where('user_id', $this->auth->id)->order('id desc')->paginate();
        $this->success('', $lists);
    }

    /**
     * @Author LK
     * @ApiTitle (取消订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="reason", type="integer", required=true, sample="", description="取消原因")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function cancel_order()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $order = Order::get($id);
        if ($order->status != 0) {
            $this->error('状态错误');
        }
        try {
            Order::where('id', $order['id'])->where('status', '0')->update(['status' => '-1', 'reason' => $reason]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * @Author LK
     * @ApiTitle (删除订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function del_order()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $order = Order::get($id);
        if ($order->status != '4') {
            $this->error('状态错误');
        }
        $res = Order::where('id', $order['id'])->where('status', '4')->update(['status' => '5']);
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }
    /**
     * @Author LK
     * @ApiTitle (配件订单详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_info()
    {
        $param = request()->param();
        extract($param);
        $data = Order::get($id);
        $this->success('', $data);
    }
    /**
     * @Author LK
     * @ApiTitle (售后原因)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function Atfer()
    {
        $lists = After::all();
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (申请售后)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="type", type="integer", required=true, sample="", description="申请类型：1=仅退款，2=退款退货")
     * @ApiParams (name="num", type="integer", required=true, sample="", description="退货数量")
     * @ApiParams (name="money", type="integer", required=true, sample="", description="退货金额")
     * @ApiParams (name="description", type="string", required=true, sample="", description="描述")
     * @ApiParams (name="refund_images", type="string", required=true, sample="", description="图片")
     * @ApiParams (name="refund_reason", type="string", required=true, sample="", description="退款原因")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function apply_service()
    {
        $param = request()->param();
        extract($param);
        $order = Order::get($id);
        $validate = new Validate([
            'id'   => 'require|gt:0',
            'type'  => 'require|gt:0',
            'num'  => 'require|gt:0',
            // 'money'  => 'require|gt:0',
            'description'  => 'require',
            'refund_reason'  => 'require',
        ], [
            'id.require'  => '参数错误',
            'type.require' => '请选择售后类型',
            'num.require' => '退货数量不能为空',
            // 'money' => '退款金额不能为空',
            'description' => '描述不能为空',
            'refund_reason' => '请选择退款原因',
        ]);
        $validate->scene(['refund' => 'id,type,money,description,refund_reason']);
        $scene = '';
        if ($type == 1) {
            $scene = 'refund';
        }
        $result = $validate->check($param, [], $scene);
        if (!$result) {
            $this->error(__($validate->getError()));
        }
        if (!$order) {
            $this->error('订单不存在');
        }
        $order->sale_status = $type;
        $order->refund_status = '1';
        $order->description = $description;
        $order->refund_num = $num;
        $order->refund_price = $money;
        $order->refund_images = $refund_images;
        $order->refund_reason = $refund_reason;
        $res = $order->save();
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }
    /**
     * @Author LK
     * @ApiTitle (配件评论)
     * @ApiMethod (POST)
     * @ApiParams (name="order_id", type="integer", required=true, sample="", description="订单id")
     * @ApiParams (name="goods_id", type="integer", required=true, sample="", description="商品id")
     * @ApiParams (name="star", type="integer", required=true, sample="", description="星级")
     * @ApiParams (name="content", type="string", required=true, sample="", description="评论内容")
     * @ApiParams (name="images", type="string", required=true, sample="", description="评论图片")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function review()
    {
        $param = request()->param();
        extract($param);
        $validate = new Validate(
            [
                'order_id' => 'require|gt:0',
                'goods_id' => 'require|gt:0',
                'star' => 'require|gt:0',
                'content' => 'require',
            ],
            [
                'order_id.require' => '参数错误',
                'goods_id.require' => '参数错误',
                'star.require' => '请星级打分',
                'content.require' => '请输入评论内容',
            ]
        );
        $result = $validate->check($param);
        if (!$result) {
            $this->error(__($validate->getError()));
        }
        $order = Order::get($order_id);
        if (!$order) {
            $this->error('订单不存在');
        }
        Db::startTrans();
        try {
            $model = new  Review();
            $order = Order::get($order_id);
            $param['user_id'] = $this->auth->id;
            $res = $model->allowField(true)->save($param);
            if ($res) {
                $order->status = '4';
                $order->save();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * @Author LK
     * @ApiTitle (评论列表)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="limit", type="integer", required=true, sample="", description="每页数量")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function review_list()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $lists = Review::with('user')->where('review.goods_id', $id)->where('state', '2')->paginate($limit ?? 10);
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (确认收货)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function take_order()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $order = Order::get(['id' => $id, 'sale_status' => '0', 'refund_status' => '0', 'user_id' => $this->auth->id]);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order['status'] != 2) {
            $this->error('订单状态错误');
        }
        $order->status = '3';
        $order->taketime = time();
        $res = $order->save();
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }
}
